/*
 * @Description:
 * @Author: ldx
 * @Date: 2022-04-29 14:23:26
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-18 18:06:45
 */
import { Tooltip } from 'antd'
import _ from 'lodash'
import { useCallback, useEffect, useRef, useState } from 'react'
interface Props {
  children: string | undefined | number | Array<string | undefined | number>
  className?: string
}
const canvas = document.createElement('canvas')
const textWidth = (text: string): number => {
  const ctx = canvas.getContext('2d')!
  ctx.font =
    '14px/1.5715 "Source Sans Pro, Helvetica Neue, Helvetica, Arial, sans-serif"'
  const width = ctx?.measureText(text).width || 0
  return width * 1.07
}
export const TextTooltip: React.FC<Props> = ({ children, className }) => {
  children = Array.isArray(children) ? children : [children]
  children = children.filter((v) => v).join(' ')
  const ref = useRef<HTMLSpanElement>(null)
  const [, forceUpdate] = useState<number>(0)
  const widith = ref.current?.offsetWidth || 0
  const text = textWidth(children + '')
  // console.log('children', children, text)

  const changeFun = useCallback(() => {
    forceUpdate(Math.random())
  }, [])
  const debounceFn = useCallback(_.debounce(changeFun, 250), [changeFun])
  useEffect(() => {
    const handler = () => {
      debounceFn()
    }
    window.addEventListener('resize', handler)
    return () => window.removeEventListener('resize', handler)
  }, [])
  return text > widith ? (
    <Tooltip title={children}>
      <span
        ref={ref}
        className={`truncate inline-block whitespace-nowrap ${className}`}
      >
        {children}
      </span>
    </Tooltip>
  ) : (
    <span ref={ref} className={`break-normal whitespace-nowrap ${className}`}>
      {children}
    </span>
  )
}
